package main

import (
	"encoding/hex"
	"errors"
	"fmt"
	"log"
	"net"
	"strings"
)

func main() {
	macBase58, err := GetFirstValidMacBase58()
	if err != nil {
		log.Fatalf("获取本地有效MAC地址失败: %v", err)
	}
	log.Printf("本地第一个有效MAC地址转换成Base58字符串是：%s", macBase58)
	testBase58Mac()
	testBase33Mac()

	// 测试 DecodeBase33FindMac
	interfaces, err := net.Interfaces()
	if err != nil {
		log.Fatalf("获取本地有效MAC地址失败: %v", err)
	}
	var mac net.HardwareAddr
	for _, inter := range interfaces {
		if (inter.Flags&net.FlagLoopback) != 0 || (inter.Flags&net.FlagUp) == 0 || len(inter.HardwareAddr) == 0 {
			continue
		}
		mac = inter.HardwareAddr
		break
	}
	if mac == nil {
		log.Fatalf("未找到有效的MAC地址")
	}
	base33 := EncodeBase33(mac)
	fmt.Printf("测试Base33编码: %s\n", base33)
	found := DecodeBase33FindMac(base33)
	if found {
		fmt.Println("DecodeBase33FindMac 测试通过：编码解码后MAC在本机网卡中")
	} else {
		fmt.Println("DecodeBase33FindMac 测试失败：编码解码后MAC不在本机网卡中")
	}
}

// 获取第一个有效（非回环、非空）MAC地址并转为Base58字符串
func GetFirstValidMacBase58() (string, error) {
	interfaces, err := net.Interfaces()
	if err != nil {
		return "", err
	}

	for _, inter := range interfaces {
		// 跳过回环接口、禁用接口、没有MAC的接口
		if (inter.Flags&net.FlagLoopback) != 0 || (inter.Flags&net.FlagUp) == 0 || len(inter.HardwareAddr) == 0 {
			continue
		}

		macHex := strings.ToUpper(hex.EncodeToString(inter.HardwareAddr))
		macBase58 := EncodeBase58(inter.HardwareAddr)
		log.Printf("[系统信息] 接口 %s 的MAC地址是：%s，Base58编码为：%s", inter.Name, macHex, macBase58)
		return macBase58, nil
	}

	return "", errors.New("未找到有效的MAC地址")
}

// 将[]byte转为Base58字符串
func EncodeBase58(data []byte) string {
	const base58Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
	var num uint64
	for _, b := range data {
		num = num<<8 + uint64(b)
	}
	if num == 0 {
		return string(base58Alphabet[0])
	}
	var result string
	for num > 0 {
		remainder := num % 58
		result = string(base58Alphabet[remainder]) + result
		num /= 58
	}
	return result
}

// Base58转回MAC地址
func DecodeBase58ToMac(base58 string) (net.HardwareAddr, error) {
	const base58Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
	alphabetIdx := map[rune]int{}
	for i, c := range base58Alphabet {
		alphabetIdx[c] = i
	}
	var num uint64
	for _, c := range base58 {
		idx, ok := alphabetIdx[c]
		if !ok {
			return nil, fmt.Errorf("非法Base58字符: %c", c)
		}
		num = num*58 + uint64(idx)
	}
	// MAC地址6字节
	mac := make([]byte, 6)
	for i := 5; i >= 0; i-- {
		mac[i] = byte(num & 0xff)
		num >>= 8
	}
	return net.HardwareAddr(mac), nil
}

// 测试代码
func testBase58Mac() {
	macBase58, err := GetFirstValidMacBase58()
	if err != nil {
		log.Fatalf("获取本地有效MAC地址失败: %v", err)
	}
	fmt.Printf("Base58编码: %s\n", macBase58)
	mac, err := DecodeBase58ToMac(macBase58)
	if err != nil {
		log.Fatalf("Base58解码失败: %v", err)
	}
	fmt.Printf("解码回MAC地址: %s\n", mac.String())
}

// 编写测试代码
// [系统信息] 接口 ETH4 的MAC地址是：000EC6CAEA9C，Base58编码为：2fhAKvj
// 本地第一个有效MAC地址转换成Base58字符串是：2fhAKvj 转回去能否转换成原来的MAC地址

// 实现Base33代码 123456789ABCDEFGHJKLMNPQRSTUVWXYZ
func EncodeBase33(data []byte) string {
	const base33Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ"
	var num uint64
	for _, b := range data {
		num = num<<8 + uint64(b)
	}
	if num == 0 {
		return string(base33Alphabet[0])
	}
	var result string
	for num > 0 {
		remainder := num % 33
		result = string(base33Alphabet[remainder]) + result
		num /= 33
	}
	return result
}

// Base33转回MAC地址
func DecodeBase33ToMac(base33 string) (net.HardwareAddr, error) {
	const base33Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ"
	alphabetIdx := map[rune]int{}
	for i, c := range base33Alphabet {
		alphabetIdx[c] = i
	}
	var num uint64
	for _, c := range base33 {
		idx, ok := alphabetIdx[c]
		if !ok {
			return nil, fmt.Errorf("非法Base33字符: %c", c)
		}
		num = num*33 + uint64(idx)
	}
	// MAC地址6字节
	mac := make([]byte, 6)
	for i := 5; i >= 0; i-- {
		mac[i] = byte(num & 0xff)
		num >>= 8
	}
	return net.HardwareAddr(mac), nil
}

// 测试Base33编码和解码
func testBase33Mac() {
	interfaces, err := net.Interfaces()
	if err != nil {
		log.Fatalf("获取本地有效MAC地址失败: %v", err)
	}
	var mac net.HardwareAddr
	for _, inter := range interfaces {
		if (inter.Flags&net.FlagLoopback) != 0 || (inter.Flags&net.FlagUp) == 0 || len(inter.HardwareAddr) == 0 {
			continue
		}
		mac = inter.HardwareAddr
		break
	}
	if mac == nil {
		log.Fatalf("未找到有效的MAC地址")
	}
	base33 := EncodeBase33(mac)
	fmt.Printf("Base33编码: %s\n", base33)
	decoded, err := DecodeBase33ToMac(base33)
	if err != nil {
		log.Fatalf("Base33解码失败: %v", err)
	}
	fmt.Printf("Base33解码回MAC地址: %s\n", decoded.String())
}

// 根据编码转回MAC地址 再根据MAC地址查询是否在本机的网卡中
func DecodeBase33FindMac(base33 string) bool {
	mac, err := DecodeBase33ToMac(base33)
	if err != nil {
		return false
	}
	interfaces, err := net.Interfaces()
	if err != nil {
		return false
	}
	for _, inter := range interfaces {
		if (inter.Flags&net.FlagLoopback) != 0 || (inter.Flags&net.FlagUp) == 0 || len(inter.HardwareAddr) == 0 {
			continue
		}
		if inter.HardwareAddr.String() == mac.String() {
			return true
		}
	}
	return false
}
